#!/usr/bin/env python
# -*- coding:utf-8 -*-


import datetime
import math

from ..models import db
from ..models.student import Student



class StudentController(Student):

    # add
    @classmethod
    def add(cls, **kwargs):
        try:
            model = Student(
                autoID=kwargs.get('autoID'),
                studentID=kwargs.get('studentID'),
                name=kwargs.get('name'),
                age=kwargs.get('age'),
                agenda=kwargs.get('agenda'),
                classID=kwargs.get('classID'),
                isDelete=kwargs.get('isDelete'),
                addTime=kwargs.get('addTime'),
                
            )
            db.session.add(model)
            db.session.commit()
            results = {
                'add_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                'autoID': model.autoID,
                
            }
            return {'code': "200", 'message': "成功！", 'data': results}
            
        except Exception as e:
            db.session.rollback()
            return {'code': "5001", 'message': "数据库错误", 'data': {'error': str(e)}}
        finally:
            db.session.close()

    # get
    @classmethod
    def get(cls, **kwargs):
        try:
            filter_list = []
            if kwargs.get('autoID') is not None:
                filter_list.append(cls.autoID == kwargs.get('autoID'))
            if kwargs.get('studentID'):
                filter_list.append(cls.studentID == kwargs.get('studentID'))
            if kwargs.get('name'):
                filter_list.append(cls.name == kwargs.get('name'))
            if kwargs.get('age') is not None:
                filter_list.append(cls.age == kwargs.get('age'))
            if kwargs.get('agenda'):
                filter_list.append(cls.agenda == kwargs.get('agenda'))
            if kwargs.get('classID') is not None:
                filter_list.append(cls.classID == kwargs.get('classID'))
            if kwargs.get('isDelete') is not None:
                filter_list.append(cls.isDelete == kwargs.get('isDelete'))
            if kwargs.get('addTime'):
                filter_list.append(cls.addTime == kwargs.get('addTime'))
            
            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))
            
            student_info = db.session.query(cls).filter(*filter_list)
            
            count = student_info.count()
            pages = math.ceil(count / size)
            student_info = student_info.limit(size).offset((page - 1) * size).all()

            results = cls.to_dict(student_info)
            return {'code': "200", 'message': "成功！", 'totalCount': count, 'totalPage': pages, 'data': results}
            
        except Exception as e:
            return {'code': "5001", 'message': "数据库错误", 'data': {'error': str(e)}}
        finally:
            db.session.close()

    # delete
    @classmethod
    def delete(cls, **kwargs):
        try:
            filter_list = []
            filter_list.append(cls.autoID == kwargs.get('autoID'))
            
            res = db.session.query(cls).filter(*filter_list).with_for_update()
            
            if not res.first():
                return {'code': "5001", 'message': "数据库错误", 'error': "数据不存在"}

            results = {
                'delete_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                'autoID': res.first().autoID,
                
            }
            res.delete()
            db.session.commit()

            return {'code': "200", 'message': "成功！", 'data': results}

        except Exception as e:
            db.session.rollback()
            
            return {'code': "5001", 'message': "数据库错误", 'data': {'error': str(e)}}
        finally:
            db.session.close()

    # update
    @classmethod
    def update(cls, **kwargs):
        try:
            filter_list = []
            filter_list.append(cls.autoID == kwargs.get('autoID'))
            
            res = db.session.query(cls).filter(*filter_list).with_for_update()

            if not res.first():
                return {'code': "5001", 'message': "数据库错误", 'error': "数据不存在"}
                
            results = {
                'update_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                'autoID': res.first().autoID,
                
            }
            
            res.update(kwargs)
            db.session.commit()
            
            return {'code': "200", 'message': "成功！", 'data': results}

        except Exception as e:
            db.session.rollback()
            
            return {'code': "5001", 'message': "数据库错误", 'data': {'error': str(e)}}
        finally:
            db.session.close()
